<template>
	<view class="bg-[#F2F2F2] px-3 pb-[75px] overflow-y-auto" :style="`height: ${screenHeight}px;`">
		<uni-data-checkbox mode="tag" v-model="current" :localdata="currentArr" selectedColor="#6699FF" class="flex py-3" />
		<uni-card is-full class="!mb-3">
			<view>
				<view v-if="current === 0" class="flex items-center justify-between">
					<view class="flex-1 grid grid-cols-2 items-center">
						<view class="py-4 flex items-center">
							<uni-icons type="contact" size="30" color="#5D6166" class="mr-2" />
							<text>{{ locationObj.contactName || '--' }}</text>
						</view>
						<view class="py-4 flex items-center">
							<uni-icons type="phone" size="30" color="#5D6166" class="mr-2" />
							<text>{{ locationObj.contactPhone || '--' }}</text>
						</view>
						<view class="py-4 col-span-2 flex items-center">
							<uni-icons type="map-pin-ellipse" size="30" color="#5D6166" class="mr-2" />
							<text>{{ locationObj.address || '--' }}</text>
						</view>
					</view>
					<uni-icons type="right" size="30" color="#5D6166" @tap="openLocation('DeliveryRef')" />
				</view>
				<view v-if="current === 1" class="flex items-center justify-between">
					<view class="flex-1 grid items-center">
						<view class="py-4">
							<text class="mr-3">{{ locationObj.selfPickupPointName || '--' }}</text>
							<text class="mr-3">{{ locationObj.contactPhone || '--' }}</text>
							<text>{{ locationObj.selfPickupPointAddress || '--' }}</text>
						</view>
					</view>
					<uni-icons type="right" size="25" color="#5D6166" @tap="openLocation('SelfPickRef')" />
				</view>
			</view>
		</uni-card>
		
		<uni-card is-full>
			<uni-forms ref="baseFormRef" :modelValue="orderObj" validate-trigger="blur" label-width="100px">
				<uni-forms-item label="货物类型:" name="cargoType" class="items-center">
					{{ packageList.length > 0 ? packageList[0].cargoType : '获取失败' }}
				</uni-forms-item>
				<uni-forms-item label="选择时效:" name="insuranceAmount" class="items-center" :rules="[{'required': true,errorMessage: '时效必填'}]">
					<uni-data-select
						class="min-w-[100px]"
						v-model="orderObj.insuranceAmount"
						:localdata="aging"
						placeholder="选择时效"
						:clear="false"
						@change="agingBlur"
					/>
				</uni-forms-item>
				<uni-forms-item label="选择承运商:" name="carrierId" class="items-center" :rules="[{'required': true,errorMessage: '承运商必填'}]">
					<uni-data-select
						class="min-w-[100px]"
						v-model="orderObj.carrierId"
						:localdata="carrier"
						placeholder="选择承运商"
						:clear="false"
					/>
				</uni-forms-item>
				<uni-forms-item label="选择付款方式:" name="paymentMethod" class="items-center" :rules="[{'required': true,errorMessage: '付款方式必填'}]">
					<uni-data-select
						class="min-w-[100px]"
						v-model="orderObj.paymentMethod"
						placeholder="选择付款方式"
						:localdata="payment"
						:clear="false"
					/>
				</uni-forms-item>
				<uni-forms-item label="选择集运劵:" name="useCollectionCoupon" class="items-center">
					<uni-data-select
						class="min-w-[100px]"
						v-model="orderObj.useCollectionCoupon"
						placeholder="选择集运劵"
						:localdata="CouponList"
						:clear="false"
					/>
				</uni-forms-item>
				<uni-forms-item label="使用积分:" name="integral" class="items-center" :rules="[{'required': true,errorMessage: '积分必填'}]">
					<uni-easyinput v-model="orderObj.integral" type="number" placeholder="请输入积分" />
				</uni-forms-item>
				<uni-forms-item name="Insured" class="items-center" :rules="[{'required': true,errorMessage: '保价必填'}]">
					<template #label>
						<view class="w-[100px] pr-3 flex flex-col">
							<text>保价(选填):</text>
							<text class="text-xs text-[red]">*保价手续费: {{ money.InsuranceHandling }}</text>
						</view>
					</template>
					<uni-easyinput v-model="orderObj.Insured" type="number" placeholder="请输入保价(选填)" @blur="InsuredBlur" />
				</uni-forms-item>
				<uni-forms-item v-if="current === 1" label="收件人:" name="reciveName" class="items-center" :rules="[{'required': true,errorMessage: '收件人必填'}]">
					<uni-easyinput v-model="orderObj.reciveName" placeholder="请输入收件人" />
				</uni-forms-item>
				<uni-forms-item v-if="current === 1" label="收件电话:" name="reciveTel" class="items-center" :rules="[{'required': true,errorMessage: '收件电话必填'}, {'pattern': /^1((34[0-8])|(8\d{2})|(([35][0-35-9]|4[579]|66|7[35678]|9[1389])\d{1}))\d{7}$/, errorMessage: '收件电话格式不正确'}]">
					<uni-easyinput v-model="orderObj.reciveTel" type="Number" placeholder="请输入收件电话" />
				</uni-forms-item>
				<uni-forms-item label="备注(选填):" name="remarks" class="items-center">
					<uni-easyinput v-model="orderObj.remarks" placeholder="请输入备注(选填)" />
				</uni-forms-item>
			</uni-forms>
		</uni-card>
		
		<uni-card
			v-for="(item, index) in packageList"
			:key="index"
			:title="item.courierNumber"
			is-full
			class="!mt-[10px]"
		 >
			<template v-slot:title>
				<uni-list>
					<view class="flex justify-between px-2 py-3">
						<label>单号: {{ item.courierNumber }}</label>
					</view>
				</uni-list>
			</template>
			
			<view class="grid grid-cols-2 gap-3">
				<text>货物名称: {{ item.cargoName || '--' }}</text>
				<text>货物类型: {{ item.cargoType || '--' }}</text>
				<text>货物数量: {{ item.cargoQuantity || '--' }}</text>
				<text>货物价值: {{ item.cargoValue || '--' }}</text>
				<text class="col-span-2">计费体积: {{ item.cargoDimensions || '--' }} (cm)</text>
				<text>实际重量: {{ item.actualWeight || '--' }} (kg)</text>
				<text>收费重量: {{ item.volumeWeight || '--' }} (kg)</text>
				<view class="col-span-2  flex justify-between">
					<text>仓租: 0</text>
					<text>超长费: {{ item.extraFee || '--' }}</text>
					<text>附加费: 0</text>
				</view>
			</view>
		</uni-card>
		
		<view class="fixed left-0 bottom-0 bg-white w-full h-[65px] px-3 flex justify-between items-center">
			<view class="text-sm flex flex-col">
				<label class="text-red">重量({{ allWeight }})kg</label>
				<label class="text-red">合计({{ allMoney }})元</label>
			</view>
			<view>
				<uv-button text="确定集运" color="#A52A2A" @tap="addOrderPick" />
			</view>
		</view>
		<uv-picker ref="DeliveryRef" :columns="DeliveryCompute" keyName="country" @confirm="pickConfirm" />
		<uv-picker ref="SelfPickRef" :columns="SelfPickCompute" keyName="destination" @confirm="pickConfirm" />
	</view>
</template>

<script setup>
	import store from '@/store'
	import { getAddress } from '@/api/modules/address.js'
	import { getCoupon } from '@/api/modules/coupon.js'
	import { getDict } from '@/api/modules/dict.js'
	import { getAging, getCalculate, getAllSum } from '@/api/modules/applyTransform.js'
	const { user, dict } = store()
	
	const current = ref(-1) // 当前地址选择 1自提点 / 0送货上门
	const currentArr = ref([{
		value: 0,
		text: '送货上门'
	},
	{
		value: 1,
		text: '自提点'
	}]) // 地址选项集合
	const aging = ref([]) // 时效数组
	const carrier = ref([]) // 承运商数组
	const payment = ref([
		{
			text: '余额支付',
			value: 1
		}, {
			text: '微信支付',
			value: 2
		}, {
			text: '支付宝支付',
			value: 3
		}
	]) // 付款方式数组
	const orderObj = ref({
		cargoType: 1, // 货品类型
		insuranceAmount: 0, // 时效
		Insured: 0, // 保价金额
		carrierId: -1, // 承运商
		paymentMethod: '', // 付款方式
		remarks: '' , // 备注
		domesticTrackingNumber: [] , // 国内单号集合
		destinationName: '' ,// 目的地名称
		reciveName: '' , // 收件人姓名
		reciveTel: 0 // 收件人电话
	}) // 申请集运订单对象
	const DeliveryRef = ref() // 送货上门弹框对象
	const SelfPickRef = ref() // 自提点弹框对象
	const baseFormRef = ref() // 基础表单对象
	const packageList = ref([]) // 传入的包裹列表
	const locationObj = ref({}) // 当前地址对象
	const money = ref({
		InsuranceHandling: 0, // 保价手续费
		DeliveryPrice: 0, // 送货价格
		SelfPickPrice: 0 // 自提价格 
	})
	const CouponList = ref([]) // 集运卷列表
	const DeliveryCompute = ref([]) // 送货上门地址列表
	
	// 自提点地址列表
	const SelfPickCompute = computed(() => {
		return [dict.pickup.map(item => { return item })]
	})
	// 获取货物类型列表
	const cargoTypeList = computed(() => {
		console.log(dict.cargoType)
		return dict.cargoType
	})
	// 获取界面高度
	const screenHeight = computed(() => {
		return uni.getSystemInfoSync().windowHeight
	})
	// 合计重量
	const allWeight = computed(() => {
		let sum = 0
		packageList.value.forEach(item => {
			sum += item.actualWeight
		})
		return sum
	})
	// 合计金额
	const allMoney = computed(() => {
		let sum = 0 // 总价
		Object.keys(money.value).forEach(item => {
			sum += money.value[item]
		})
		return sum
	})
	
	// 获取传入的参数
	onMounted(() => {
		// 获取用户地址
		getAddress(user.userInfo.userId).then(res => {
			DeliveryCompute.value = [res.data] // 地址列表
			current.value = 0 // 确保初始化更新送货上门还是自提点以更新时效集合和承运商集合
		}).catch(err => {
			DeliveryCompute.value = [[]] // 地址列表
		})
		// 获取集运卷列表
		getCoupon({ userId: user.userInfo.userId }).then(res => {
			CouponList.value = res.rows.map(item => {
				return {
					text: item.denomination + '元',
					value: item.id
				}
			})
		}).catch(err => {
			CouponList.value = []
		})
		
		// 获取上个页面传入的值
		const instance = getCurrentInstance().proxy
		const eventChannel = instance.getOpenerEventChannel();

		eventChannel.on('applyOrder', function(data) {
			packageList.value = data
		})
	})
	
	// 时效改变触发
	const agingBlur = async (e) => {
		let otherPrice = 0
		Object.keys(money.value).forEach(item => {
			otherPrice += money.value[item]
		})
		const carrierFind = carrier.value.find(item => { return item.value = orderObj.value.carrierId }) // 找出单条承运商数据
		const insuranceAmountFind = aging.value.find(item => { return item.value = orderObj.value.insuranceAmount }) // 找出单条航班时效数据
		
		// 所有配置
		const config = {
			userId: user.userInfo.userId, // 用户id
			cargoType: packageList.value.length > 0 ? packageList.value[0].cargoType : '', // 货物类型
			domesticTrackingNumber: packageList.value.map(item => { return item.courierNumber }), // 国内快递单号集合
			moneyRequest: otherPrice, // 其他费用
			serviceMethodId: current.value, // 服务方式
			paymentMethodId: orderObj.value.paymentMethod, // 付款方式ID
			source: 3, // 订单来源 app: 3
			remarks: orderObj.value.remarks, // 备注
			userName: user.userInfo.userName, // 会员昵称
			useCollectionCoupon: orderObj.value.useCollectionCoupon, // 集运劵
			destinationNameId: current.value === 0 ? locationObj.value.countryId : locationObj.value.destinationId, // 目的地ID
			recipient: current.value === 0 ? locationObj.value.countryId : locationObj.value.selfPickupPointName, // 收货人姓名
			mobilePhone: locationObj.value.contactPhone, // 收货人电话
			address: current.value === 0 ? locationObj.value.countryId : locationObj.value.selfPickupPointAddress, // 地址
			carrierId: carrierFind.value, // 承运商ID
			carrierCompany: carrierFind.text, // 承运商名称
			flightEffectivenessId: insuranceAmountFind.value,
			flightEffectiveness: insuranceAmountFind.text,
			addressId: current.value === 0 ? orderObj.value.addressId : orderObj.value.destinationId, // 收货人地址ID
			pickupId: orderObj.value.destinationId, // 自提点id
			insuranceAmount: orderObj.value.Insured, // 保价
			pickupName: orderObj.value.destination,// 自提点名称
			insuranceServiceFee: money.value.InsuranceHandling // 保价手续费
		}
		// 送货上门
		const browerCongfig = {
			userId: user.userInfo.userId, // 用户id
			cargoType: packageList.value.length > 0 ? packageList.value[0].cargoType : '', // 货物类型
			domesticTrackingNumber: packageList.value.map(item => { return item.courierNumber }), // 国内快递单号集合
			moneyRequest: otherPrice, // 其他费用
			serviceMethodId: current.value, // 服务方式
			paymentMethodId: orderObj.value.paymentMethod, // 付款方式ID
			source: 3, // 订单来源
			remarks: orderObj.value.remarks, // 备注
			userName: user.userInfo.userName, // 会员昵称
			useCollectionCoupon: orderObj.value.useCollectionCoupon, // 集运劵
			destinationNameId: current.value === 0 ? locationObj.value.countryId : locationObj.value.destinationId, // 目的地ID
			recipient: current.value === 0 ? locationObj.value.countryId : locationObj.value.selfPickupPointName, // 收货人姓名
		}
		// 自提点
		// const res = await getAllSum()
		console.log(config)
	}
	// 计算保价手续费用和送货费用/保价手续费和自提费用 || 0: 送货 5:自提 1: 保价
	const computeSum = async (type, field) => {
		let config = {
			cargoTypeId: packageList.value[0].cargoTypeId,
			destinationId: current.value === 0 ? locationObj.value.countryId : locationObj.value.destinationId, // locationObj.value.id
			shopId: user.userInfo.shopId,
			timeEfficiencyId: orderObj.value.insuranceAmount,
			warehouseId: packageList.value[0].warehouseId
		}
		config.feeType = type
		// calculateWeight字段为保价手续费的时候传入保价值, 为送货和自提的时候为重量
		config.calculateWeight = type === 1 ? orderObj.value.Insured : allWeight.value
		const price = 0 // 计算金额
		
		const res = await getCalculate(config) // 计算保价
		money.value[field] = res.freight
	}
	// 保价失去焦点触发
	const InsuredBlur = async (e) => {
		let config = {
			feeType: 1,
			calculateWeight: orderObj.value.Insured,
			cargoTypeId: packageList.value.length > 0 ? packageList.value[0].cargoTypeId : 0,
			destinationId: locationObj.value.id, // locationObj.value.id
			shopId: user.userInfo.shopId,
			timeEfficiencyId: orderObj.value.insuranceAmount,
			warehouseId: packageList.value.length > 0 ? packageList.value[0].warehouseId : 0
		}
		const res = await getCalculate(config) // 计算保价
		money.value.InsuranceHandling = res.freight // 赋值保价手续费
	}
	// 打开地址列表
	const openLocation = (ref) => {
		if(ref === 'DeliveryRef') {
			DeliveryRef.value.open()
		} else {
			SelfPickRef.value.open()
		}
	}
	// 关闭地址列表, 更新当前地址选择对象
	const pickConfirm = (e) => {
		console.log(e)
		locationObj.value = e.value[0]
		console.log(locationObj.value)
	}
	// 申请集运
	const addOrderPick = () => {
		baseFormRef.value.validate().then(res => {
			console.log(res)
		}).catch(err => {
			console.log('err', err);
		})
	}
	
	// 当送货上门/自提点更改时候且不为空时默认选中第一个地址
	watch(current, (val) => {
		// 判断是否是送货上门还是自提点
		aging.value = [] // 时效列表赋值为空
		carrier.value = [] // 承运商列表赋值为空
		orderObj.value.insuranceAmount = -1 // 时效为空
		orderObj.value.carrierId = -1 // 承运商
		if(val === 0) {
			locationObj.value = DeliveryCompute.value[0].length > 0 ? DeliveryCompute.value[0][0] : {}
		} else {
			locationObj.value = SelfPickCompute.value[0].length > 0 ? SelfPickCompute.value[0][0] : {}
		}
		console.log(locationObj.value)
	})
	watch(() => locationObj.value, async (newValue) => {
		// 判断是否是送货上门还是自提点获取时效和承运商的时候
		const res = await getAging({ destinationId: current.value === 0 ? newValue.countryId : newValue.destinationId })
		// 获取时效里列表和承运商列表
		const agingObj = res.rows.map(item => {
			return {
				text: item.timely,
				value: item.timelyId
			}
		})
		const carrierObj = res.rows.map(item => {
			return {
				text: item.carrierName,
				value: item.carrierId
			}
		})
		
		// 数组对象去重时效承运商
		const map = new Map()
		aging.value = agingObj.filter(v => !map.has(v.value) && map.set(v.value, v))
		carrier.value = carrierObj.filter(v => !map.has(v.value) && map.set(v.value, v))
	}, { deep: true })
</script>

<style scoped>
	
</style>
